﻿using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using Microsoft.Identity.Client;
using Android.Content;
using DailyPoetryX.Droid.Services.Implementations;
using DailyPoetryX.Services;
using GalaSoft.MvvmLight.Ioc;

namespace DailyPoetryX.Droid {
    [Activity(Label = "DailyPoetryX", Icon = "@mipmap/icon",
        Theme = "@style/MainTheme", MainLauncher = true,
        ConfigurationChanges =
            ConfigChanges.ScreenSize | ConfigChanges.Orientation,
        LaunchMode = LaunchMode.SingleTask)]
    [IntentFilter(new[] {Intent.ActionView},
        Categories = new[] {Intent.CategoryDefault, Intent.CategoryBrowsable},
        DataScheme = "com.thesallab.dailypoetryx",
        DataHost = "dailypoetryx.auth0.com",
        DataPathPrefix = "/android/com.thesallab.dailypoetryx/callback")]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.
        FormsAppCompatActivity {
        protected override void OnCreate(Bundle savedInstanceState) {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            SimpleIoc.Default
                .Register<IAuthenticationService, AuthenticationServiceAndroid
                >();
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
            App.AuthUIParent = this;
        }

        public override void OnRequestPermissionsResult(int requestCode,
            string[] permissions,
            [GeneratedEnum] Android.Content.PM.Permission[] grantResults) {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode,
                permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions,
                grantResults);
        }

        protected override void OnActivityResult(int requestCode,
            Result resultCode, Intent data) {
            base.OnActivityResult(requestCode, resultCode, data);
            AuthenticationContinuationHelper
                .SetAuthenticationContinuationEventArgs(requestCode, resultCode,
                    data);
        }

        protected override void OnNewIntent(Intent intent) {
            base.OnNewIntent(intent);
            Auth0.OidcClient.ActivityMediator.Instance.Send(intent.DataString);
        }
    }
}